"""
@author: xxw
@file: user.py
@time: 2023/8/1 19:11
"""
from flask import request
from flask_restful import Resource, Api
from forms.user import UserForm, LoginForm
from libs.auth import create_token, auth_required
from models.user import UserInfo
from libs.response import generate_response
from . import user_bp

api = Api(user_bp)

# 用户注册视图
class UserRegister(Resource):
    @auth_required
    def post(self):
        data = request.json
        form = UserForm(data=data)
        if form.validate():
            UserInfo.create_user(
                username=data.get("username"),
                password=form.password.data)
            return generate_response(code=0, message="注册成功")
        else:
            return generate_response(code=1, message=form.errors)
api.add_resource(UserRegister,'/user')

# 登录视图
class LoginView(Resource):
    def post(self):
        data = request.json
        form = LoginForm(data=data)
        user = form.validate()
        if user:
            # 验证通过，生成token
            token = create_token(user.user_id)

            return generate_response(message="login success", code=0, data={"token": token,
                                                                            "username": user.username})
        else:
            return generate_response(message="login fail", code=1)

api.add_resource(LoginView, "/login")